package ar.edu.unlu.sistemas.movirdroid.business.index;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import ar.edu.unlu.sistemas.movirdroid.business.util.IndexHelper;
import ar.edu.unlu.sistemas.movirdroid.business.vo.TermFrecuencyVO;
import ar.edu.unlu.sistemas.movirdroid.business.vo.WordVO;

public class Indexer {
	
	
	private static Indexer instance;
	
	public static Indexer getInstance(){
		if (instance == null) {
			instance = new Indexer();
		}
		return instance;
	}
	
	private IndexController index;
	
	private Indexer() {
		this.index = IndexController.getInstance();
	}
	
	/**
	 * Indexa un nuevo archivo
	 * @param fr (El lector del archivo)
	 * @param fileName (El nombre del archivo)
	 */
	public Set<String> addFile(FileReader fr, String fileName) {
		if (this.index.findDocumentByName(fileName) == null) {
			this.index.insertDoc(fileName);
			try {
				Map<String,TermFrecuencyVO> terms = IndexHelper.createIndexFromFile(fr);
				this.insertTfs(terms, fileName);
				return terms.keySet();
			} catch (FileNotFoundException fne) {

			} catch (IOException ioe) {

			}

		}
		return null;
	}
	
	private void insertTfs(Map<String,TermFrecuencyVO> terms, String docName) {
		String key;
		TermFrecuencyVO tfVO;
		Collection<WordVO> words = this.index.findWordsByNames(terms.keySet());
		Iterator<String> keys = terms.keySet().iterator();
		while (keys.hasNext()) {
			key = keys.next();
			tfVO = terms.get(key);
			if (!words.contains(tfVO.getWord())) {
				this.index.insertWord(tfVO.getWord().getName());
			}
			this.index.insertTf(docName,key,tfVO.getValue());
		}
	}
	
}
